package com.xxxx.util;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * java根据 url获取 json对象
 * @author openks
 * @since 2013-7-16
 *  需要添加java-json.jar才能运行
 */
public class GetCid {

    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        } finally {
            is.close();
            // System.out.println("同时 从这里也能看出 即便return了，仍然会执行finally的！");
        }
    }


    public String[] getcid(String animeid)throws IOException, JSONException {
        JSONObject json = readJsonFromUrl("https://api.acplay.net/api/v2/bangumi/"+animeid);
        JSONArray a=json.getJSONObject("bangumi").getJSONArray("episodes");
        String[] b=new String[a.length()];
        for(int i=0;i<a.length();i++){
            b[i]=a.getJSONObject(i).get("episodeId").toString();
        }
        return b;
    }
}